import { ZYSDK } from "../../../../ZYSDK";
import adModel from "../../../main/view/adView/adModel";
import { soundMgr } from "../../def/sound";
import { ZYEventMgr } from "../../manager/YLEventMgr";
import gameModel from "../../model/gameModel";
import { ZYNetMgr } from "../../server/ZYNetMgr";
import wxPackage from "../wxPackage";

/**
 * 接口使用方法 ADEvent.xx
 * 微信各种API接口
 * @author: xj.huang
 * @date: 2021/08/03 10:14:26
 */
class WXAPIManager {
    /**腾讯API 如：QQ ，WX */
    private _tencentApi: any = window['wx'];
    protected _tercentAppName = "微信";
    protected _systemInfo: _getSystemInfoSyncReturnValue;
    private _launchOptions: ZYSDK.IWXLaunchOptions
    private _MenuButton: wx.WXUIRect;
    private _preReqAuthorTime = 0;
    private _videoAd: wx.RewardedVideoAd;

    constructor() { }
    /**启动 */
    public deploy(): void {
        if (!this._tencentApi) {
            console.warn("当前不在微信环境")
            return
        }
        this._tencentApi.showShareMenu({ withShareTicket: true });
        this._systemInfo = this._tencentApi.getSystemInfoSync();
        this._launchOptions = this._tencentApi.getLaunchOptionsSync();
        this._MenuButton = this._tencentApi.getMenuButtonBoundingClientRect();
        this._tencentApi.onShow(this.wxOnShow.bind(this))
        this._tencentApi.onHide(this.wxOnHide.bind(this))
        // this._tencentApi.onhidden(this.onhidden.bind(this))
        
    }
    /**微信登录 */
    public wxLogin() {

    }
    get systemInfo() {
        return this._systemInfo;
    }
    /**获取启动参数 */
    get launchOptions() {
        return this._launchOptions
    }
    get menuButton() {
        return this._MenuButton
    }

    /**
     * 
     * @param id 
     * @param isMore 
     */
    private wxOnShow(res) {
        soundMgr.playBgm();
        soundMgr.isMuteMusic = true;
        soundMgr.isMuteMusic = false;
        soundMgr.playBgm();
        ZYEventMgr.emit(GameEvent.ON_CHANGE_BANNER)
        console.log("回来场景值",res)
    }
    private wxOnHide(){
        // soundMgr.stopBgm()
    }
    private onhidden(){
        ZYEventMgr.emit(GameEvent.ON_CHANGE_BANNER)
    }
    /**************************************************************************************
     * 
     * 
     *  @param id 广告ID
     * @param isMore 是否多格子 
     * 创建广告。请通过 wx.getSystemInfoSync() 
     * - 返回对象的 SDKVersion 判断基础库版本号 >= 2.11.1 后再使用该 API。
     * - 每次调用该方法创建原生模板广告都会返回一个全新的实例
     * @see - https://developers.weixin.qq.com/minigame/dev/api/ad/wx.createCustomAd.html
     * 
     * 
     * 
     **************************************************************************************/
    async createCustomAd(id, isMore): Promise<wx.CustomAd | any> {
        // if (!this.isSupportBannerAd) return;
        if (!id || !this._tencentApi || !Laya.Browser.onWeiXin || !this._tencentApi.createCustomAd) return null;
        return new Promise<wx.CustomAd>(($resolved) => {
            const currGrid: wx.CustomAd = this._tencentApi.createCustomAd({
                adUnitId: id,
                adIntervals: 30,
                style: {
                    left: isMore ? (WXAPIMgr.systemInfo.screenWidth - 360) / 2 : this.menuButton.left + 20,
                    top: isMore ? WXAPIMgr.systemInfo.screenHeight - 125 : this.menuButton.top + 50,
                    width: isMore ? WXAPIMgr.systemInfo.screenWidth : 300,
                    fixed: true
                },
            })
            currGrid.onError(err => {
                $resolved(undefined);
            })
            currGrid.onLoad(() => {
                $resolved(currGrid);
            })

        });
    }
    /**************************************************************************************
     * 
     * 
     * 
     *  
     * 广告bannerAPI
     * @see 微信 https://developers.weixin.qq.com/minigame/dev/api/ad/wx.createBannerAd.html
     * 
     * 
     * 
     * 
     * 
     **************************************************************************************/
    async createBannerAd(id): Promise<unknown> {
        // if (!this.isSupportBannerAd) return;
        if (!id || !this._tencentApi) return null
        return new Promise<unknown>(($resolved) => {
            const banner: wx.BannerAd = this._tencentApi.createBannerAd({
                adUnitId: id,
                style: {
                    left: 0,
                    top: WXAPIMgr.systemInfo.screenHeight - 125 - 20,
                    width: WXAPIMgr.systemInfo.screenWidth,
                    height: Laya.Browser.clientHeight * 0.9 * 0.9
                }
            });
            banner.onError((res) => {
                $resolved(undefined);
                this.bannerMsg(res.errCode)

            });
            banner.onLoad(() => {
                $resolved(banner);

            });
            banner.onResize(($res?: { width: number, height: number }) => {
                if ($res) {
                    //qq部分是通过参数传过来的：@see https://q.qq.com/wiki/develop/game/API/ad/BannerAd.html#onresize
                    banner.style.realWidth = $res.width;
                    banner.style.realHeight = $res.height;
                    banner.style.top = WXAPIMgr.systemInfo.screenHeight - $res.height - 20;
                    adModel.bnnerheight = banner.style.realHeight || $res.height
                } else {
                    const realHeight = banner.style.realHeight + .1;
                    // if (!YLADMgr.normalBannerHegiht) YLADMgr.normalBannerHegiht = realHeight;
                    banner.style.top = WXAPIMgr.systemInfo.screenHeight - realHeight;
                }
            });

        });
    }


    /**
     * 创建视频ID
    * @see 微信  https://developers.weixin.qq.com/minigame/dev/api/ad/wx.createRewardedVideoAd.html
    */
    public async createVideoAd(id, _this, callBack): Promise<unknown> {
        if (!this._tencentApi || !id) return null;
        return new Promise<unknown>(($resolved) => {
            this._videoAd?.destroy();
            this._videoAd = this._tencentApi.createRewardedVideoAd({ adUnitId: id });

            const onload = () => {
                if (this._videoAd) {
                    this._videoAd.offLoad(onload);
                    $resolved(this._videoAd);
                    console.log("视频加载成功");
                }
            };
            this._videoAd.onLoad(onload);
            this._videoAd.onError((res) => {
                this.bannerMsg(res.errCode)
                this._videoAd?.destroy();
                this._videoAd = undefined;
                $resolved(undefined);
            });
            /** 
             * $res有可能为空
             * @see https://developers.weixin.qq.com/minigame/dev/api/ad/RewardedVideoAd.onClose.html 
             * */
            this._videoAd.onClose((res: { isEnded: boolean } | undefined) => {
                if (res && res.isEnded || res === undefined) {
                    console.warn("用户已观看完成,可以有奖励")
                } else {
                    console.log("中途退出广告，没有奖励")
                }
                callBack && callBack.call(_this, res ? (res.isEnded ? 1 : 0) : 1)
                // this._onVideoCloseCallback && this._onVideoCloseCallback($res ? ($res.isEnded ? 1 : 0) : 1);
                // this._onVideoCloseCallback = undefined;
                this._videoAd.load();//关闭之后load下一条
            });
            this._videoAd.load();
        });
    }

    /**
     * 
     * 跳转小程序之间的跳转
     * @sse  https://developers.weixin.qq.com/minigame/dev/api/navigate/wx.navigateToMiniProgram.html
     * 
     * 
     */
    async navigateToMiniProgram(appId, path, dataSource?) {
        if (!this._tencentApi || !Laya.Browser.onWeiXin) {
            return console.warn("当前是web端:不支持跳转其它小游戏")
        }
        return new Promise<unknown>(($resolved) => {
            let ToMini = this._tencentApi.navigateToMiniProgram({
                appId: appId,
                path: path,
                extraData: {
                    foo: 'bar'
                },
                envVersion: 'release',
                async success(res) {
                    $resolved(ToMini);
                    // 打开成功 这里需要上报到服务端
                    let options = window['wx'] && window['wx']['getLaunchOptionsSync']() || {};
                    await ZYNetMgr.export({
                        application_id: ZYSDK.config.server.APPID,
                        openid: gameModel.loginData.openid,
                        scene_id: gameModel.loginData.scene_id,
                        channel_id: options.query.channel_id || '',
                        is_new: gameModel.loginData.is_new,
                        reg_time: gameModel.loginData.reg_time,
                        export_id: dataSource?.id,
                        data: {
                            'name': dataSource?.name
                        },
                    })
                    // console.log("导出成功", options)
                },
                fail(res) {
                    $resolved(undefined);
                    console.warn("点击取消：", res);
                    //做一些失败处理
                    // console.log("点击取消：", name);

                },
                complete(res) {
                    console.info("跳转其它小游戏结束lll", res,appId, path, dataSource);
                }
            });
        }); 
    }

    private bannerMsg(code) {

        let info = "";
        switch (code) {
            case 1000:
                info = "后端错误调用失败";
                break;
            case 1001:
                info = "参数错误";
                break;
            case 1001:
                info = "广告单元无效";
                break;
            case 1003:
                info = "内部错误";
                break;
            case 1004:
                info = "无合适的广告";
                break;
            case 1005:
                info = "广告组件审核中";
                break;
            case 1006:
                info = "广告组件被驳回";
                break;
            case 1007:
                info = "广告组件被封禁";
                break;
            case 1008:
                info = "广告单元已关闭";
                break;
        }
        console.warn("误信息:" + info)
    }

    /** 
     * 登录
     * @see 微信 https://developers.weixin.qq.com/minigame/dev/api/open-api/login/wx.login.html
     */
    public async login(): Promise<ZYSDK.IWXLoginResult> {
        return new Promise<ZYSDK.IWXLoginResult>(($resolved, $rejected) => {
            this._tencentApi.login({
                success: ($res: ZYSDK.IWXLoginResult) => {
                    if ($res.code) {
                        console.log(`【${this._tercentAppName}】登录成功`);
                        $resolved($res);
                    } else {
                        $rejected(`${this._tercentAppName}登录失败，code不存在！`);
                    }
                },
                fail: () => $rejected(`${this._tercentAppName}登录失败，接口调用失败！`)
            });
        });

    }

    /**setStorage */
    public async setStorage(key, data: object | string) {
        if (!this._tencentApi) return;
        return await this._tencentApi.setStorageSync(key, data)
    }
    /**异步加载微信包 作用域 */
    public async asyncLoad(packages, caller?, callBack?: Function) {
        return await wxPackage.asyncLoad(packages, caller, callBack)
    }
}
/**
 * 微信各种API接口
 * @author: xj.huang
 * @date: 2021/08/03 10:14:26
 */
export const WXAPIMgr = new WXAPIManager();